package com.mgface.tech;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author wanyuxiang
 * @version 1.0
 * @project netty_fly
 * @create 2020-06-18 18:06
 **/
public class EchoServer {
    private final int port;
    public EchoServer(int port){
        this.port = port;
    }

    private void start() throws InterruptedException {
        EventLoopGroup g = new NioEventLoopGroup();
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(g).channel(NioServerSocketChannel.class)
            .localAddress(new InetSocketAddress(port))
            .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    socketChannel.pipeline().addLast(new EchoServerHandler());
                }
            });
           ChannelFuture future =  bootstrap.bind().sync();
           future.channel().closeFuture().sync();
        }finally {
            g.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        EchoServer server = new EchoServer(8888);
        server.start();
    }
}
